﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TdolDemo_QBZ.Models.Task;
using TdolDemo_QBZ.Models;

namespace TdolDemo_QBZ.Repository
{
    public class TdolTaskUnitListRepository : ITdolTaskUnitListRepository
    {
        //get list
        public List<TaskWithUnitModel> GetTaskList(int taskId)
        {
            //var tasks = new List<TaskWithUnitModel>();
            var db = new sqltestContext();
            var tasks = (new TdolTaskListRepository()).GetTaskList(taskId).ToList();
            var taskids = tasks.Select(s => s.TaskId).Distinct().ToList();
            var units = (new TdolUnitRepository()).GetUnitInTask(taskids).ToList();
            var taskwithunits = tasks.GroupJoin(units, t => t.TaskId, u => u.TaskId, (t, u) => new TaskWithUnitModel
            {
                CreateBy = t.CreateBy,
                CreateOn = t.CreateOn,
                Description = t.Description,
                Guid = t.Guid,
                IsDelete = t.IsDelete,
                OpenIntervalEnd = t.OpenIntervalEnd,
                OpenIntervalStart = t.OpenIntervalStart,
                RegionId = t.RegionId,
                Remarks = t.Remarks,
                Status = t.Status,
                TaskId = t.TaskId,
                TestDateId = t.TestDateId,
                TimeStamp = t.TimeStamp,
                units = u.ToList(),
                UpdateBy = t.UpdateBy,
                UpdateOn = t.UpdateOn
            }).ToList();


            return taskwithunits;
        }
        //add
        public int AddTaskList(TaskWithUnitModel task)
        {
            var db = new sqltestContext();
            var tbtask = new TbTdolTaskList {
                CreateBy = task.CreateBy,
                CreateOn = task.CreateOn,
                Description = task.Description,
                Guid = task.Guid,
                IsDelete = task.IsDelete,
                OpenIntervalEnd = task.OpenIntervalEnd,
                OpenIntervalStart = task.OpenIntervalStart,
                RegionId = task.RegionId,
                Remarks = task.Remarks,
                Status = task.Status,
                TestDateId = task.TestDateId
            };
            db.TbTdolTaskList.Add(tbtask);
            if (db.SaveChanges() > 0)
            {
                return tbtask.TaskId;
            }
            else
            {
                return 0;
            }
            
        }

    }
}
